package com.glepoch.springbootsecuritymybatis.utils;

import com.glepoch.springbootsecuritymybatis.compoment.constant.statuscode.GlobalStatusCode;
import com.glepoch.springbootsecuritymybatis.compoment.execption.impl.CommonExecption;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 基于spring BeanUtils进行二次封装。对象对象对拷，数组数组对拷
 * @author: ygl
 * @time: 2020/12/16 16:01
 */
public class CopyBeanUtils {

    public static <K> K beanToBean(Object source, Class<K> targetClass) {
        if (source == null) {
            return null;
        }
        if (source instanceof List) {
            throw new CommonExecption(GlobalStatusCode.INCONSISTENT_DATATYPE);
        }
        K t = null;
        try {
            t = targetClass.newInstance();
            BeanUtils.copyProperties(source, t);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return t;
    }

    public static <K> List<K> listToList(List sources, Class<K> targetClass) {
        if (sources == null) {
            return null;
        }
        if (!(sources instanceof List)) {
            throw new CommonExecption(GlobalStatusCode.INCONSISTENT_DATATYPE);
        }
        List<K> list = new ArrayList<>();
        K t = null;
        try {
            for (Object source : sources) {
                t = targetClass.newInstance();
                BeanUtils.copyProperties(source, t);
                list.add(t);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return list;
    }

    //示例
/*    public static void main(String[] args) throws CommonExecption {
        List<BasicinfoEntity> basicinfoEntities =new ArrayList<>();
        BasicinfoEntity basicinfoEntity1=new BasicinfoEntity();
        basicinfoEntity1.setBiId("1");
        basicinfoEntity1.setBiCustname("zhang1");

        BasicinfoEntity basicinfoEntity2=new BasicinfoEntity();
        basicinfoEntity2.setBiId("2");
        basicinfoEntity2.setBiCustname("zhang2");
        basicinfoEntities.add(basicinfoEntity1);
        basicinfoEntities.add(basicinfoEntity2);

        CopyBeanUtils.beanToBean(basicinfoEntity1, BasicinfoEntity.class);

        List<BasicInfoVO> basicInfoVOS = CopyBeanUtils.listToList(basicinfoEntities, BasicInfoVO.class);
        System.out.println(basicInfoVOS);
    }*/
}
